document.addEventListener("DOMContentLoaded", function() {
    const ServerUrl = 'http://110.41.71.43:8080';
    // 获取三个按钮的引用
    const buttons = document.querySelectorAll('button');
    const button1 = document.getElementById('task1');
    const button2 = document.getElementById('task2');
    const button3 = document.getElementById('task3');
    const latestPriceElement = document.getElementById('latest-Price');
    const taskElement = document.getElementById('task-display');
    const taskRecentlyElement = document.getElementById('task-recently');
    const orderListElement = document.getElementById('orders-list');
    // const dailyProfitListElement = document.getElementById('daily-profit');
    const tableBody = document.querySelector("#data-table tbody");
    
    // 渲染数据到页面
    // container.innerHTML = jsonToHtml(jsonData);
    
    // 定时器参数
    let intervalId;
    let taskRecentProfitIntervalId;
    let latestPriceIntervalId;

    // 默认展示任务详情
    showLatestPrice(latestPriceElement)
    showDefaultTask(taskElement)
    showDefaultTaskRecentProfit(taskRecentlyElement)
    showDefaultTaskOrders(orderListElement)
    // showDefaultDailyProfits(dailyProfitListElement)
    showDefaultDailyProfits(tableBody)
    
    // 定义点击事件处理函数
    function handleClickButton1() {
        console.log('按钮 1 被点击了！');
        buttons.forEach(btn => btn.classList.remove('selected'));
        // 为当前点击的按钮添加 "selected" 类
        this.classList.add('selected');

        displayTask(1, taskElement);
        displayTaskRecentProfit(1, taskRecentlyElement);
        showTaskOrders(1, orderListElement)
        // showDailyProfits(1, dailyProfitListElement)
        showDailyProfits(1,tableBody)
    }

    function handleClickButton2() {
        console.log('按钮 2 被点击了！');
        buttons.forEach(btn => btn.classList.remove('selected'));
        // 为当前点击的按钮添加 "selected" 类
        this.classList.add('selected');

        displayTask(2, taskElement);
        displayTaskRecentProfit(2, taskRecentlyElement);
        showTaskOrders(2, orderListElement)
        // showDailyProfits(2, dailyProfitListElement)
        showDailyProfits(2,tableBody)
    }

    function handleClickButton3() {
        console.log('按钮 3 被点击了！');
        buttons.forEach(btn => btn.classList.remove('selected'));
        // 为当前点击的按钮添加 "selected" 类
        this.classList.add('selected');

        displayTask(3, taskElement);
        displayTaskRecentProfit(3, taskRecentlyElement);
        showTaskOrders(3, orderListElement)
        // showDailyProfits(3, dailyProfitListElement)
        showDailyProfits(3,tableBody)
    }

    // 为每个按钮添加点击事件监听器
    button1.addEventListener('click', handleClickButton1);
    button2.addEventListener('click', handleClickButton2);
    button3.addEventListener('click', handleClickButton3);

    function displayTask(taskNo, element) {
        var url = ServerUrl + '/task/' + taskNo;
        console.log(url)
        fetch(url) // 使用一个公开API作为示例
        .then(response => response.json())
        .then(data => {
            // 渲染数据到页面
            element.innerHTML = '<h class="h1">任务运行数据：</h><br><br>'
            element.innerHTML += jsonToHtml(data);
        })
        .catch(error => console.error('Error fetching data:', error));
    
        setIntervalTask(taskNo, element)
    }

    // 显示24小时盈利情况
    function displayTaskRecentProfit(taskNo, element) {
        var url = ServerUrl + '/taskrecentprofit/' + taskNo;
        console.log(url)
        fetch(url) // 使用一个公开API作为示例
        .then(response => response.json())
        .then(data => {
            // 渲染数据到页面
            element.innerHTML = '<h class="h1">最近24小时盈利情况: </h><br><br>'
            element.innerHTML += jsonToHtml(data);
        })
        .catch(error => console.error('Error fetching data:', error));
    
        setIntervalTaskRencentProfit(taskNo, element)
    }

    // 将 JSON 数据转换为 HTML 字符串
    function jsonToHtml_save(jsonObj) {
        let html = '';
        for (const key in jsonObj) {
            if (jsonObj.hasOwnProperty(key)) {
                const value = jsonObj[key];
                html += `<div>
                <br>
                <span class="key">${key}:</span> 
                <span class="value">${typeof value === 'object' ? jsonToHtml(value) : value}</span>
                </div>`;
            }
        }
        return html;
    }

    function jsonToHtml(jsonObj) {
        let html = '';
        for (const key in jsonObj) {
            if (jsonObj.hasOwnProperty(key)) {    
                const value = jsonObj[key];      
                html +=`<div class="key-value">
                <span class="key">${key}:</span> <span class="value">${value}</span>
                </div>`
            }
        }
        return html;
    }

    // 设置在运行任务定时器
    function setIntervalTask(taskNo, element) {
        // 如果已经有定时器运行，则先清除
        if (intervalId) {
            clearInterval(intervalId);
        }
        intervalId = setInterval(function() {
            fetch(ServerUrl + '/task/'+ taskNo) // 替换为实际的API URL
                .then(response => response.json())
                .then(data => {
                    // 更新页面显示的数据
                    element.innerHTML = '<h class="h1">任务运行数据：</h><br><br>'
                    element.innerHTML += jsonToHtml(data);
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                    element.textContent = 'Failed to load data.';
                });
        }, 30000); // 每5秒执行一次
    
        // 当用户离开页面时，清除定时器
        window.addEventListener('beforeunload', function() {
            clearInterval(intervalId);
        });
    }

    // 设置最近24小时盈利定时器
    function setIntervalTaskRencentProfit(taskNo, element) {
        // 如果已经有定时器运行，则先清除
        if (taskRecentProfitIntervalId) {
            clearInterval(taskRecentProfitIntervalId);
        }
        taskRecentProfitIntervalId = setInterval(function() {
            fetch(ServerUrl + '/taskrecentprofit/'+ taskNo) // 替换为实际的API URL
                .then(response => response.json())
                .then(data => {
                    // 更新页面显示的数据
                    element.innerHTML = '<h class="h1">最近24小时盈利情况: </h><br><br>'
                    element.innerHTML += jsonToHtml(data);
                })
                .catch(error => {
                    console.error('Error fetching data:', error);
                    element.textContent = 'Failed to load data.';
                });
        }, 30000); // 每5秒执行一次
    
        // 当用户离开页面时，清除定时器
        window.addEventListener('beforeunload', function() {
            clearInterval(taskRecentProfitIntervalId);
        });
    }

    // 设置当前价格定时器
    function setLatestPriceInterval(element) {
        // 如果已经有定时器运行，则先清除
        if (latestPriceIntervalId) {
            clearInterval(latestPriceIntervalId);
        }
        latestPriceIntervalId = setInterval(function() {
            fetch(ServerUrl + '/latestprice') // 替换为实际的API URL
            .then(response => response.json())
            .then(data => {
                // 更新页面显示的数据
                element.innerHTML = `<h class="h1">当前价格：</h><br><br>`
                element.innerHTML += jsonToHtml(data);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                element.textContent = 'Failed to load data.';
            });
        }, 5000); // 每5秒执行一次
    
        // 当用户离开页面时，清除定时器
        window.addEventListener('beforeunload', function() {
            clearInterval(latestPriceIntervalId);
        });
    }

    // 显示最新价格
    function showLatestPrice(element) {
        fetch(ServerUrl + '/latestprice') // 替换为实际的API URL
            .then(response => response.json())
            .then(data => {
                // 更新页面显示的数据
                element.innerHTML = `<h class="h1">当前价格：</h><br><br>`
                element.innerHTML += jsonToHtml(data);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                element.textContent = 'Failed to load data.';
            });
        setLatestPriceInterval(element)
    }

    // 默认显示在运行任务
    function showDefaultTask(element) {
        fetch(ServerUrl + '/task/1') // 替换为实际的API URL
            .then(response => response.json())
            .then(data => {
                // 更新页面显示的数据
                element.innerHTML = `<h class="h1">任务运行数据：</h><br><br>`
                element.innerHTML += jsonToHtml(data);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                element.textContent = 'Failed to load data.';
            });
        setIntervalTask(1, element);
    }

    
    // 默认显示最近24小时盈利情况
    function showDefaultTaskRecentProfit(element) {
        fetch(ServerUrl + '/taskrecentprofit/1') // 替换为实际的API URL
            .then(response => response.json())
            .then(data => {
                // 更新页面显示的数据
                element.innerHTML = '<h class="h1">最近24小时盈利情况: </h><br><br>'
                element.innerHTML += jsonToHtml(data);
            })
            .catch(error => {
                console.error('Error fetching data:', error);
                element.textContent = 'Failed to load data.';
            });
        setIntervalTaskRencentProfit(1, element);
    }

    // 默认显示最近订单列表
    function showDefaultTaskOrders(element) {
        // const orderListElement = document.getElementById('orders-list');
        fetch(ServerUrl + '/orders/1')
        .then(response => response.json())
        .then(orders => {
            orders.forEach(order => {
                displayOrder(order, element);
            });
        })
        .catch(error => console.error('Error fetching orders:', error));
    }

    

    // 显示最近订单列表
    function showTaskOrders(taskNo, element) {
        element.innerHTML = ''
        fetch(ServerUrl + '/orders/' + taskNo)
        .then(response => response.json())
        .then(orders => {
            orders.forEach(order => {
                displayOrder(order, element);
            });
        })
        .catch(error => console.error('Error fetching orders:', error));
    }

    function displayOrder(order, element) {
        const listItem = document.createElement('li');
        listItem.classList.add('order-item');
    
        for (const key in order) {
            if (order.hasOwnProperty(key)) {
                const keyValue = document.createElement('div');
                keyValue.classList.add('key-value');
                keyValue.innerHTML = `<span class="li-key">${key}:</span> <span class="li-value">${order[key]}</span>`;
                listItem.appendChild(keyValue);
            }
        }
    
        element.appendChild(listItem);
    }

    // 显示最近日计利润列表
    // function showDailyProfits(taskNo, element) {
    //     element.innerHTML = ''
    //     fetch('http://110.41.71.43:8080/dailyprofits/' + taskNo)
    //     .then(response => response.json())
    //     .then(dailyProfits => {
    //         dailyProfits.forEach(dailyProfit => {
    //             displayDailyProfit(dailyProfit, element);
    //         });
    //     })
    //     .catch(error => console.error('Error fetching orders:', error));
    // }

    // 默认显示最近日计利润列表
    // function showDefaultDailyProfits(element) {
    //     fetch('http://110.41.71.43:8080/dailyprofits/1')
    //     .then(response => response.json())
    //     .then(dailyProfits => {
    //         dailyProfits.forEach(dailyProfit => {
    //             displayDailyProfit(dailyProfit, element);
    //         });
    //     })
    //     .catch(error => console.error('Error fetching orders:', error));
    // }

    // function displayDailyProfit(dailyProfit, element) {
    //     const listItem = document.createElement('li');
    //     listItem.classList.add('daily-profit');
    
    //     for (const key in dailyProfit) {
    //         if (dailyProfit.hasOwnProperty(key)) {
    //             const keyValue = document.createElement('div');
    //             keyValue.classList.add('key-value');
    //             keyValue.innerHTML = `<span class="li-key">${key}:</span> <span class="li-value">${dailyProfit[key]}</span>`;
    //             listItem.appendChild(keyValue);
    //         }
    //     }
    //     element.appendChild(listItem);
    // }

    function showDailyProfits(taskNo, element) {
        element.innerHTML = ''
        fetch(ServerUrl + '/dailyprofits/' + taskNo)
        .then(response => response.json())
        .then(dailyProfits => {
            dailyProfits.forEach(dailyProfit => {
                const row = document.createElement('tr');
                Object.values(dailyProfit).forEach(value => {
                    const cell = document.createElement('td');
                    cell.textContent = value;
                    row.appendChild(cell);
                });
                tableBody.appendChild(row);
            });
        })
        .catch(error => console.error('Error fetching orders:', error));
    }

    function showDefaultDailyProfits(element) {
        // const tableBody = document.querySelector("#data-table tbody");
        fetch(ServerUrl + '/dailyprofits/1')
        .then(response => response.json())
        .then(dailyProfits => {
            dailyProfits.forEach(dailyProfit => {
                const row = document.createElement('tr');
                Object.values(dailyProfit).forEach(value => {
                    const cell = document.createElement('td');
                    cell.textContent = value;
                    row.appendChild(cell);
                });
                element.appendChild(row);
            });
        })
        .catch(error => console.error('Error fetching orders:', error));
    }
});







